package web;

import pojo.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    UserService userService =new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String remember = request.getParameter("remember");
    User user =userService.login(username,password);
    if(user == null)
    {
        request.setAttribute("msg","用户名或密码错误");
        request.getRequestDispatcher("/login.jsp").forward(request,response);
    }
    else
    {
        if("1".equals(remember))
        {   //写入cookie用户不用再次输入用户名和密码
            Cookie c_username = new Cookie("username",username);
            Cookie c_password = new Cookie("password",password);
            response.addCookie(c_username);
            response.addCookie(c_password);

        }
        //保存到session里面去
        HttpSession session = request.getSession();
        session.setAttribute("user",user);

        response.sendRedirect("/demo2_war_exploded/selectAllServlet");
    }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
    }
}
